import {
  getAction,
  httpAction
} from '@/api/manage'

let timer = null

const state = {
  desData: {}, // 最新一次告警数据
  lastUpdateTime: '', // 最后一次成功时间（可选）
  activeInfo: false, //群解调主/备
}

const mutations = {
  SET_ALARM(state, payload) {
    state.desData = payload
    state.lastUpdateTime = new Date().toLocaleTimeString()
  },
  SET_ACTIVE(state, payload) {
    state.activeInfo = payload
  }
}

const actions = {
  // 真正请求接口的方法
  async loadRecentAlarmStatus({
    commit,
    dispatch
  }) {
    console.log('【alarm】开始调接口')
    const res = await getAction('dcpr/dcprPassagewayHistoryInfo/getRecentAlarmStatus')
    console.log('【alarm】接口返回', res)
    if (res.success && typeof res.result !== 'string') {
      commit('SET_ALARM', res.result)
      if (res.result.snrAlarmLevel === 'LEVEL_1' &&
        res.result.freqOffsetAlarmLevel === 'LEVEL_1' &&
        res.result.syncByteAlarmLevel === 'LEVEL_1') {
        console.log('【alarm】触发自动修复')
        await dispatch('autoFix')
      }
    }
    return res // <-- 这里必须 return
  },

  // 自动修复
  async autoFix({
    rootState
  }) {
    try {
      // 1. 先发频偏测试包
      const res = await httpAction('/plan/qlTestPlan/add', {
        endTdh: '34',
        startTdh: '34',
        symbolRate: '900',
        testMode: '导频模式',
        errorSourceData: ''
      }, 'post')

      if (!res.success) throw new Error(res.message || '频偏测试失败')
      setTimeout(async () => {
        // 2. 再发导频工作模式包
        const channelCode = rootState.alarm.activeInfo ? '群解调' : '群解调备'
        const temp = {
          id: 3,
          label: '导频工作模式',
          packageCode: '603-解调器-MAC层至物理层参数设置-导频工作模式',
          nmcPackageGridValues: [{
            gridCode: '603-指令字段内容',
            packageGridValue: Number(1).toString(16).toUpperCase()
          }]
        }
        const params = {
          channelCode,
          packageCode: temp.packageCode,
          nmcPackageGridValues: temp.nmcPackageGridValues
        }
        const result = await httpAction('/channel/nmcChannelInfo/sendPackage', params, 'post')
        if (result.success) {
          console.log('【autoFix】导频工作模式下发成功')
        } else {
          console.error('【autoFix】导频工作模式下发失败：', result.message)
        }
      }, 1000 * 60 * 2)

    } catch (e) {
      console.error('【autoFix】异常：', e)
    }
  },
  //获取群解调主/备
  async getActiveInfo({
    commit,
    dispatch
  }) {
    const res = await getAction('nmc/activeInfo/list')
    let id = 1
    if (res.success && res.result.records.length > 0) {
      let list = res.result.records || []
      let info = list.find(item => item.id == id)
      console.log('获取到了主备信息')
      commit('SET_ACTIVE', info.active == '主' ? true : false)
    }
  },

  // 启动全局 10 分钟轮询
  startGlobalTimer({
    dispatch
  }) {
    if (timer) clearInterval(timer) // 1. 清旧
    dispatch('loadRecentAlarmStatus') // 3. 立即一次
    dispatch('getActiveInfo')
    timer = setInterval(() => {
      dispatch('loadRecentAlarmStatus')
      dispatch('getActiveInfo')
    }, 10 * 60 * 1000)
  },

  // 停止轮询
  stopGlobalTimer() {
    clearInterval(timer)
    timer = null
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}